package com.tokenplus.thai.utils.update;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.tokenplus.thai.ProjectApplication;
import com.tokenplus.thai.ProjectConfig;
import com.tokenplus.thai.adata.version.RevDataAppVersion;
import com.tokenplus.thai.launch.AppUpdateActivity;

import java.io.File;

public class ZHIVersionIMPL {

    /**
     * apk安装格式地址
     */
    public static final String INSTALL_APK_URL_SUFIX = ".apk";

    /**
     * 谷歌商店格式地址
     */
    public static final String GOOGLE_PLAY_URL_PREFIX = "https://play.google.com/store/apps/details?id=";

    public static String productLink;
    public static String productApkLocalPath;

    public static ZHIVersionIMPL getInstance() {
        return instance;
    }

    private static final ZHIVersionIMPL instance = new ZHIVersionIMPL();

    @SuppressLint("NewApi")
    public static boolean openOnGooglePlayStore(String url) {
        if (TextUtils.isEmpty(url)) {
            Log.e(ZHIVersionIMPL.class.getSimpleName(), "GoogleMarket: URL not found");
            return false;
        }
        if (isGooglePlayUrl(url)) {
            try {
                final String GOOGLE_PLAY = "com.android.vending";
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                intent.setPackage(GOOGLE_PLAY);
                if (intent.resolveActivity(ProjectApplication.instance.getPackageManager()) != null) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    ProjectApplication.instance.startActivity(intent);
                    return true;
                } else {
                    Intent intent2 = new Intent(Intent.ACTION_VIEW);
                    intent2.setData(Uri.parse(url));
                    if (intent2.resolveActivity(ProjectApplication.instance.getPackageManager()) != null) {
                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        ProjectApplication.instance.startActivity(intent2);
                        return true;
                    } else {
                        Log.e(ZHIVersionIMPL.class.getSimpleName(), "GoogleMarket Intent not found");
                        return false;
                    }
                }
            } catch (ActivityNotFoundException activityNotFoundException1) {
                activityNotFoundException1.printStackTrace();
                Log.e(ZHIVersionIMPL.class.getSimpleName(), "GoogleMarket Intent not found");
                return false;
            }
        }
        return false;
    }

    public static void openOnBrowser(String url) {
        try {
            if (TextUtils.isEmpty(url)) {
                Log.e(ZHIVersionIMPL.class.getSimpleName(), "openOnBrowser: URL not found");
                return;
            }
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (intent.resolveActivity(ProjectApplication.instance.getPackageManager()) != null) {
                ProjectApplication.instance.startActivity(intent);
            } else {
                ProjectApplication.instance.startActivity(Intent.createChooser(intent, "Please select a browser to open"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isInstallApkUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        if (StringUtil.safeString(url).toLowerCase().endsWith(INSTALL_APK_URL_SUFIX)) {
            return true;
        }

        String suffix = url.substring(url.lastIndexOf("."));
        return suffix.contains("apk");
    }

    public static boolean isGooglePlayUrl(String url) {
        return StringUtil.safeString(url).toLowerCase().startsWith(GOOGLE_PLAY_URL_PREFIX);
    }

    public static String getDownloadDir() {
        String path = null;
        String apkSaveDir = "aitoolapk";
        try {
            File dataDir = ProjectApplication.instance.getFilesDir();
            path = dataDir.getAbsolutePath() + File.separator + apkSaveDir;

            File gTargetDir = new File(path);
            if (!gTargetDir.exists()) {
                gTargetDir.mkdirs();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return path;
    }

    public static String getApkSavePath() {
        String dir = getDownloadDir() + File.separator;
        String apkPath = dir + "aitoolfile.apk";
        productApkLocalPath = apkPath;
        return apkPath;
    }

    public static boolean startInstallApk(String productApkLocalPath) {
        return ZHIInstallAPK.installApk(productApkLocalPath);
    }

    public static boolean isAppNeedUpdate(Context context, RevDataAppVersion revDataAppVersion) {
        //测试
//        revDataAppVersion.setVersion("10");
//        revDataAppVersion.setLinkUrl("https://vnd.obs.ap-southeast-1.myhuaweicloud.com/collect_vnd_r12.apk");

        if (TextUtils.isEmpty(revDataAppVersion.getLinkUrl())) {
            return false;
        }

        try {
            ZHIVersionIMPL.productLink = StringUtil.safeString(revDataAppVersion.getLinkUrl());

            int oriInt = ProjectConfig.appVersion;
            String gpVersion = revDataAppVersion.getVersion();
            if (TextUtils.isEmpty(gpVersion)) {
                gpVersion = "0";
            }

            int gpInt = Integer.parseInt(gpVersion);
            if (gpInt > oriInt) {
                Intent intent = new Intent(context, AppUpdateActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
